/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * collectOrder.java
 *
 * Created on Oct 19, 2010, 10:03:51 PM
 */

package cat200;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JOptionPane;
import javax.swing.Timer;

/**
 *
 * @author peichia
 */
public class collectOrder extends javax.swing.JFrame {

	Timer timer = new Timer (4000, new TimerListener());
	
	private static String dbURL = "jdbc:derby://localhost:1527/sample;create=true;user=app;password=app";   
    private static Connection conn = null;
    private static Statement stmt = null;
    DecimalFormat dp = new DecimalFormat("#0.00");
   
    private static String invNo = "";
    private static Double amt = 0.00;
	private static Double depos = 0.00;
	private static Double balance1 = 0.00;

    /** Creates new form collectOrder */
    public collectOrder() {
    	super("Customer Collect Order");
        initComponents();
        setLocationRelativeTo(null);
        createConnection();
        update();
        setTimer();
        jProgressBar1.setVisible(false);
        //JOptionPane.showMessageDialog(null, "Please insert the invoice number!");
    }
    
    private static void createConnection()
    {
        try
        {
            Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
            //Get a connection
            conn = DriverManager.getConnection(dbURL); 
        }
        catch (Exception except)
        {
            except.printStackTrace();
        }
    }
    
    private ResultSet getResultSet(String doubt)
    {
        createConnection();
        ResultSet outcome = null;
        try
        {
            stmt = conn.createStatement();
            outcome = stmt.executeQuery(doubt);
        }
        catch (SQLException ex)
        {
        	ex.printStackTrace();
        }
        return outcome;
    }
    

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        invNum = new javax.swing.JTextField();
        search = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        total = new javax.swing.JLabel();
        deposit = new javax.swing.JLabel();
        balance = new javax.swing.JLabel();
        cash = new javax.swing.JTextField();
        change = new javax.swing.JLabel();
        date = new javax.swing.JLabel();
        jProgressBar1 = new javax.swing.JProgressBar();
        jLabel9 = new javax.swing.JLabel();
        pay = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        cusName = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        cancel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(700, 500));
        getContentPane().setLayout(null);
        getContentPane().add(invNum);
        invNum.setBounds(170, 80, 70, 30);

        search.setText("SEARCH");
        search.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchActionPerformed(evt);
            }
        });
        getContentPane().add(search);
        search.setBounds(250, 80, 90, 27);

        jLabel4.setText("Total Amount    : RM");
        getContentPane().add(jLabel4);
        jLabel4.setBounds(200, 230, 140, 30);

        jLabel5.setText("Deposit             : RM");
        getContentPane().add(jLabel5);
        jLabel5.setBounds(200, 270, 140, 30);

        jLabel6.setText("Balance             : RM");
        getContentPane().add(jLabel6);
        jLabel6.setBounds(200, 310, 140, 30);

        jLabel7.setText("Cash Received : RM");
        getContentPane().add(jLabel7);
        jLabel7.setBounds(200, 350, 140, 30);

        jLabel8.setText("Change             : RM");
        getContentPane().add(jLabel8);
        jLabel8.setBounds(200, 390, 140, 30);
        getContentPane().add(total);
        total.setBounds(350, 230, 90, 30);
        getContentPane().add(deposit);
        deposit.setBounds(350, 270, 80, 30);
        getContentPane().add(balance);
        balance.setBounds(350, 310, 80, 30);
        getContentPane().add(cash);
        cash.setBounds(350, 350, 100, 30);
        getContentPane().add(change);
        change.setBounds(350, 390, 100, 30);
        getContentPane().add(date);
        date.setBounds(475, 40, 180, 20);
        getContentPane().add(jProgressBar1);
        jProgressBar1.setBounds(250, 440, 150, 20);

        jLabel9.setText("Please insert the invoice number.                           Date :");
        getContentPane().add(jLabel9);
        jLabel9.setBounds(80, 40, 600, 20);

        pay.setText("PAY");
        pay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                payActionPerformed(evt);
            }
        });
        getContentPane().add(pay);
        pay.setBounds(460, 350, 66, 27);

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null}
            },
            new String [] {
                "Num", "Code", "Cake Type", "Order Date", "Collect Date", "Amt (RM)"
            }
        ));
        jScrollPane1.setViewportView(table);
        table.getColumnModel().getColumn(0).setPreferredWidth(40);
        table.getColumnModel().getColumn(2).setPreferredWidth(110);

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(80, 130, 530, 100);

        jLabel3.setText("Invoice No : ");
        getContentPane().add(jLabel3);
        jLabel3.setBounds(80, 80, 90, 30);
        getContentPane().add(cusName);
        cusName.setBounds(480, 80, 140, 30);

        jLabel1.setText("Customer Name : ");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(350, 80, 130, 30);

        jLabel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "COLLECT ORDER", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 3, 24), new java.awt.Color(44, 42, 225))); // NOI18N
        getContentPane().add(jLabel2);
        jLabel2.setBounds(40, 10, 620, 420);
        getContentPane().add(cancel);
        cancel.setBounds(0, 0, 700, 500);

        pack();
    }// </editor-fold>

    private void searchActionPerformed(java.awt.event.ActionEvent evt) {
    	
        invNo = invNum.getText();
    	String name = "";
    	String col3 ="",col4="";
    	int memID = 0;
    	
        
        int cusId = 0;
        cusName.setText(name);

        String queryString;
        queryString = "SELECT CUS_ID,INV_DATE,INV_DUEDATE,MEM_ID,INV_DEPOSIT FROM APP.INVOICE WHERE INV_NUM ="+invNo+"";

        System.out.println(queryString);
        ResultSet achieve = getResultSet(queryString);

        //search for the existence of the invoice
            try
            {
            	  if (achieve.next()) 
            	  {
            		 cusId = achieve.getInt(1);
            		 col3 = achieve.getString(2);
            		 col4 = achieve.getString(3);
            		 memID = achieve.getInt(4);
            		 //amt = achieve.getDouble(4);
            		 depos = achieve.getDouble(5);
            	  }
            }
            catch (SQLException sqlExcept)
            {
                sqlExcept.printStackTrace();
            }
            
            System.out.println(col3);
            System.out.println(col4);
            System.out.println(amt);
            System.out.println(depos);
            
            
            if (cusId == 0)
            {
            	JOptionPane.showMessageDialog(null, "INVALID INVOICE NUMBER!");
            	this.setVisible(false);
            	new Main(Main.col1).setVisible(true);
            }
            
            else
            {
            	//display customer id
            	Double sum = 0.00;
            	String query;
                query = "SELECT CUS_NAME FROM APP.CUSTOMER WHERE CUS_ID ="+cusId+"";

                System.out.println(query);
                ResultSet rset1 = getResultSet(query);

                    try
                    {
                    	  if (rset1.next()) 
                    	  {
                    		 cusName.setText(rset1.getString(1));
                    	  }
                    }
                    catch (SQLException sqlExcept)
                    {
                        sqlExcept.printStackTrace();
                    }
                    
                  
                //display invoice details into the table
                    try
                    {
                    	System.out.println("success");
                        int col0,col1;
                        String col2;
                        double col5;
                        
                        
                        String queryString1;
                        queryString1 = "SELECT SPECIAL_CODE, SPECIAL_TYPE, SPECIAL_PRICE FROM APP.SPECIAL WHERE INV_NUM = "+invNo+"";

                        System.out.println(queryString1);
                        ResultSet rset = getResultSet(queryString1);

                        
                        System.out.println(rset);

                        int i = 0;
                        String price;
                        
                        
                        while(rset.next())
                        {
                        	col0 = i+1;
                        	table.setValueAt(col0, i, 0);
                            col1 = rset.getInt(1);
                            table.setValueAt(col1, i, 1);
                            col2 = rset.getString(2);
                            table.setValueAt(col2, i, 2);
                            
                            table.setValueAt(col3, i, 3);
                            
                            table.setValueAt(col4, i, 4);
                            col5 = rset.getDouble(3);
                            sum = sum + col5;
                            price = dp.format(col5);
                            col5 = Double.parseDouble(price);
                            table.setValueAt(col5, i, 5);
                           
                          // table.insertRow(i, new Object[]{col0,col1,col2,col3,col4,col5,col6});
                            i++;
                        }
                        conn.close();
                    }
                    catch(Exception e)
                    {
                        System.out.println("ERROR : " + e.getMessage());
                        e.printStackTrace();
                    }   
                    
                    String Amt;
                    if (memID==0)
                    {
                    Amt = dp.format(sum);
                    total.setText(Amt);
                    }
                    
                    else
                    {
                    	 Amt = dp.format(0.9*sum);
                         total.setText(Amt);
                    }
                    
                    sum = Double.parseDouble(Amt);
                    String Depos = dp.format(depos);
                    deposit.setText(Depos);
                    balance1 = sum - depos;
                    String balance2 = dp.format(balance1);
                    balance.setText(balance2);
            }//end else
    }

    private void payActionPerformed(java.awt.event.ActionEvent evt) {
    	String pay = cash.getText();
    	
    	if (pay.equals(""))
    	{
    		JOptionPane.showMessageDialog(null, "ERROR! CASH PAID CAN'T BE NULL!");
    	}
    	
    	else
    	{
    	
    	Double payment = Double.parseDouble(String.valueOf(pay));
    	
    	Double change2 = payment - balance1;
    	
    	if(change2<0)
    	{
    		JOptionPane.showMessageDialog(null, "INVALID AMOUNT OF CASH PAID!");
    	}
    	
    	else
    	{
    	String chg = dp.format(change2);
    	change.setText(chg);
    	
    	//update invoice table
    	String invPaid = "Y";
    	String Amt = total.getText();
   	 	try
   	   	{
   	   		createConnection();
   	   		
   	   		stmt = conn.createStatement();
   	   		String sql1;
   	   	    sql1 = "UPDATE INVOICE SET INV_DEPOSIT="+Amt+",INV_PAID='"+invPaid+"' WHERE INV_NUM="+invNo+"";
   	   	    stmt.executeUpdate(sql1);
   	        System.out.println(sql1);
   	   	}
   	   	catch(Exception e)
   	   	{
   	   	    System.out.println("ERROR : " + e.getMessage());
   	   	    e.printStackTrace();
   	   	} 
   	   	
    	
    	jProgressBar1.setValue(100);
        jProgressBar1.setString("Printing...");
        jProgressBar1.setStringPainted(true);
        jProgressBar1.setVisible(true);
        jProgressBar1.setIndeterminate(true);
        
        timer.start();
    	}
    	}
    }
    
    public void setTimer() {
        int messageTimeout = 1000;
        timer1 = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                update();
            }

        });
        timer1.restart();
    }

    public void update() {
        Date currentTime = new Date();

        time++;
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy  hh:mm:ss");
        String dateString = formatter.format(currentTime);

        date.setText(dateString);
        //JOptionPane.showMessageDialog(null, "test3");
    }
    public int time = 0;
    public Timer timer1;
    
    public void stop_timer() {
	    this.setVisible(false);
    	timer.stop();
    }
    private class TimerListener implements ActionListener{
 	   public void actionPerformed(ActionEvent e){
 		   
 	    new Main(Main.col1).setVisible(true);
 	    stop_timer();
 	   } 
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new collectOrder().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JLabel balance;
    private javax.swing.JLabel cancel;
    private javax.swing.JTextField cash;
    private javax.swing.JLabel change;
    private javax.swing.JLabel cusName;
    private javax.swing.JLabel date;
    private javax.swing.JLabel deposit;
    private javax.swing.JTextField invNum;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton pay;
    private javax.swing.JButton search;
    private javax.swing.JTable table;
    private javax.swing.JLabel total;
    // End of variables declaration

}
